var selectedMenuName,selectOrgid;
var userRole = '' 
var applyTanleData = []
// 获取当前登录用户状态

function initAnalysisMenu() {
    // （0  普通用户  1   部门管理员   2  系统管理员）
    var resultsIsManager = sendAjax(modelURL + "user/getUserIsManager", "POST", {
        userNo: portaluserno
    });
    if (resultsIsManager.code == 200) {
        userRole = resultsIsManager.data.ISMANAGER
    } else {
        return null;
    }
    var results = sendAjax(modelURL + "apply/getApplyCatalog", "POST", {
        deptId: portaluserdept
    });
    if (results.code == 200) {
        var menu = results.data,
            html = "";;
            selectedMenuName = menu["专题应用"][0].NAME;
            html += '<li class="layui-menu-item-group layui-menu-item-down">';
            html += '<div class="layui-menu-body-title">专题应用<i class="layui-icon layui-icon-up"></i>';
            html += '</div><ul>';
            for (var i = 0;i < menu["专题应用"].length; i++){
                if(menu["专题应用"][i].NAME != undefined){
                    if(i == "0"){
                        html += '<li class="layui-menu-item-checked"><div class="layui-menu-body-title">' + menu["专题应用"][i].NAME + '</div></li>';
                    }else{
                        html += '<li><div class="layui-menu-body-title">' + menu["专题应用"][i].NAME + '</div></li>';
                    }
                }
            }
            html += '</ul></li>';
            html += '<li class="layui-menu-item-group layui-menu-item-down">';
            html += '<div class="layui-menu-body-title">通用分析<i class="layui-icon layui-icon-up"></i>';
            html += '</div><ul>';
            for (var i = 0;i < menu["通用分析"].length; i++){
                if(menu["通用分析"][i].NAME != undefined){
                    html += '<li><div class="layui-menu-body-title">' + menu["通用分析"][i].NAME + '</div></li>';
                }
            }
            html += '</ul></li>';
            html += '<li class="layui-menu-item-group layui-menu-item-down">';
            html += '<div class="layui-menu-body-title">其他<i class="layui-icon layui-icon-up"></i>';
            html += '</div><ul>';
            for (var i = 0;i < menu["其他"].length; i++){
                if(menu["其他"][i].NAME != undefined){
                    html += '<li  attrOrgid = '+ menu["其他"][i].ORG_ID +' ><div class="layui-menu-body-title">' + menu["其他"][i].NAME + '</div></li>';
                }
            }
            html += '</ul></li>';


        // for (var k in menu) {
        //     if (num == "0") {
        //         selectedMenuName = menu[k][0].NAME;
        //     }
        //     html += '<li class="layui-menu-item-group layui-menu-item-down">';
        //     html += '<div class="layui-menu-body-title">' + k + '<i class="layui-icon layui-icon-up"></i>';
        //     html += '</div><ul>';
        //     for (var i = 0;i < menu[k].length; i++){
        //         if(menu[k][i].NAME != undefined){
        //             if(i == "0" && num == "0"){
        //                 if(menu[k][i].ORG_ID){
        //                     selectOrgid = menu[k][i].ORG_ID
        //                     html += '<li class="layui-menu-item-checked" attrOrgid = '+ menu[k][i].ORG_ID +' ><div class="layui-menu-body-title">' + menu[k][i].NAME + '</div></li>';
        //                 }else{
        //                     html += '<li class="layui-menu-item-checked"><div class="layui-menu-body-title">' + menu[k][i].NAME + '</div></li>';
        //                 }
        //             }else{
        //                 if(menu[k][i].ORG_ID){
        //                     html += '<li  attrOrgid = '+ menu[k][i].ORG_ID +' ><div class="layui-menu-body-title">' + menu[k][i].NAME + '</div></li>';
        //                 }else{
        //                     html += '<li><div class="layui-menu-body-title">' + menu[k][i].NAME + '</div></li>';
        //                 }
        //             }
        //         }
        //     }
        //     html += '</ul></li>';
        //     num++;
        // }
        
        $("#analysisMenu").html(html);
    } else {
        layui.layer.msg("获取工具类失败！");
    }
    if(selectOrgid){
        fillAppListContent(selectedMenuName,null,selectOrgid);
    }else{
        fillAppListContent(selectedMenuName);
    }
    layui.dropdown.on('click(analysisMenu)', function(options) {
        var thisElem = $(this);
        selectedMenuName = thisElem.text();
        if($(this).attr("attrOrgid")){
            selectOrgid= thisElem.attr("attrOrgid")
            fillAppListContent(selectedMenuName,null,selectOrgid);
        }else{
            fillAppListContent(selectedMenuName);
            selectOrgid = null;
        }
    });
}
//填充右侧服务列表内容
function fillAppListContent(menuName,name,Orgid){
    var data;
    if(name){
        if(Orgid){
            data = getDataList(menuName,name,Orgid);

        }else{
            data = getDataList(menuName,name);

        }
    }else{
        if(Orgid){
            data = getDataList(menuName,null,Orgid);

        }else{
            data = getDataList(menuName,null);
        }
    }
    var totalNum = data.length;
    var TitleContentHTML, OneContentHTML, abstractContentHtml, btnContentHTML;
    laypage.render({
        elem: 'laypage',
        count: totalNum,
        theme: '#1E9FFF',
        limit: 12,
        layout: ['count', 'prev', 'page', 'next', 'refresh', 'skip'],
        jump: function (obj, first) {
            //当分页被切换时触发，函数返回两个参数：obj（当前分页的所有选项值）、first（是否首次，一般用于初始加载的判断）
            var html = '';
            var thisData = [];
            thisData = data.concat().splice(obj.curr * obj.limit - obj.limit, obj.limit);
            if (thisData.length == "0") {
                html = "<div style='width: 100%;height: 100%;text-align: center;'>当前检索结果内容为空！</div>"
            } else {
                for (var i in thisData) {
                    var item = thisData[i];
                    TitleContentHTML = '<div class = "TitleContentHTML"><span>' + item.NAME + '</span>';
                    btnContentHTML = '<div class = "btnContentHTML">'
                    //判断是否有权限运行,ISDEPT=1的则整个部门都有权限，不需要再判断ISMANAGER，
                    var isDept = 0;
                    if (item.ISDEPT) {
                        isDept = item.ISDEPT;
                    }
                    var isPermission = item.ISMANAGER
                    var status = item.STATUS
                    if (isDept == "1") {
                        OneContentHTML = '<div class = "OneContentHTML"><button type="button" class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs" style = "cursor: default !important;">可运行</button></div>'
                        btnContentHTML += '<div class = "permissionInfo" ><span attrName = ' + item.NAME + ' fkMenu=' + item.NO + ' attrID=' + item.ID + '>查看授权信息</span></div>'
                        btnContentHTML += '<button name=' + item.NAME + ' fkMenu=' + item.NO + '  type="button" class="layui-btn layui-btn-sm layui-btn-warm runningBtn">运行</button></div>'
                        //判断是否是已收藏的
                        //0:未收藏
                        //1:已收藏
                        var isCollected = item.ISFAVORITE
                        if (isCollected == "1") {
                            TitleContentHTML += '<span class="collectServiceImg collectActive" attrID=' + item.NO + '></span></div>'
                        } else {
                            TitleContentHTML += '<span class="collectServiceImg" attrID=' + item.NO + '></span></div>'
                        }
                    } else {
                        // ISMANAGER
                        // 0：需要申请审核
                        // 1：审核通过
                        // STATUS
                        // 空：需要申请审核
                        // 0：审核中
                        // 1：审核通过
                        // 2：审核未通过
                        if (userRole > 0) {
                            OneContentHTML = '<div class = "OneContentHTML"><button type="button" class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs" style = "cursor: default !important;">可运行</button></div>'
                            btnContentHTML += '<div class = "permissionInfo" ><span attrName = ' + item.NAME + ' fkMenu=' + item.NO + ' attrID=' + item.ID + '>查看授权信息</span></div>'
                            btnContentHTML += '<button name=' + item.NAME + ' fkMenu=' + item.NO + '  type="button" class="layui-btn layui-btn-sm layui-btn-warm runningBtn">运行</button></div>'
                            //判断是否是已收藏的
                            //0:未收藏
                            //1:已收藏
                            var isCollected = item.ISFAVORITE
                            if (isCollected == "1") {
                                TitleContentHTML += '<span class="collectServiceImg collectActive" attrID=' + item.NO + '></span></div>'
                            } else {
                                TitleContentHTML += '<span class="collectServiceImg" attrID=' + item.NO + '></span></div>'
                            }
                        } else {
                            if (isPermission == "1") {
                                OneContentHTML = '<div class = "OneContentHTML"><button type="button" class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs" style = "cursor: default !important;">可运行</button></div>'
                                btnContentHTML += '<div class = "permissionInfo" ><span attrName = ' + item.NAME + ' fkMenu=' + item.NO + ' attrID=' + item.ID + '>查看授权信息</span></div>'
                                btnContentHTML += '<button name=' + item.NAME + ' fkMenu=' + item.NO + '  type="button" class="layui-btn layui-btn-sm layui-btn-warm runningBtn">运行</button></div>'
                                //判断是否是已收藏的
                                //0:未收藏
                                //1:已收藏
                                var isCollected = item.ISFAVORITE
                                if (isCollected == "1") {
                                    TitleContentHTML += '<span class="collectServiceImg collectActive" attrID=' + item.NO + '></span></div>'
                                } else {
                                    TitleContentHTML += '<span class="collectServiceImg" attrID=' + item.NO + '></span></div>'
                                }
                            } else if (isPermission == "0") {
                                if (status == "0") {
                                    btnContentHTML += '<div class = "doingPermission" ><span>审核中...</span></div>'
                                } else {
                                    btnContentHTML += '<div class = "applyPermission" ><span attrName = ' + item.NAME + ' fkMenu=' + item.NO + ' attrID=' + item.ID + '>申请运行</span></div>'
                                }
                                // btnContentHTML += '<div class = "applyPermission" ><span attrName = '+ item.NAME +' fkMenu='+ item.NO +' attrID='+ item.ID +'>申请运行</span></div>'
                                btnContentHTML += '<button name=' + item.NAME + ' fkMenu=' + item.NO + '  type="button" class="layui-btn layui-btn-sm layui-btn-disabled runningBtn">运行</button></div>'
                                OneContentHTML = '<div class = "OneContentHTML"><button type="button" class="layui-btn layui-btn-disabled layui-btn-xs" style = "cursor: default !important;">可运行</button></div>'
                                TitleContentHTML += '</div>'
                            }
                        }

                    }
                    abstractContentHtml = '<div class = "abstractContentHtml"><span>数据说明：</span><span style="color: #BDBDBD;">无</span></div>'
                    html += '<div  class="OneContentDiv">';
                    html += '<div class = "ContentHtml" id="">';
                    html += TitleContentHTML + abstractContentHtml + OneContentHTML + btnContentHTML;
                    html += '</div></div>';
                }
            }
            $('#rightMainContent').html(html);
            initEvents()
        }
    });
}

function initEvents() {
    //点击收藏图标
    $(".collectServiceImg").click(function (e) {
        var collect = $(e.target).hasClass("collectActive");
        var itemId = $(e.target).attr("attrID");
        var ISFAVORITE;
        if (collect) { //执行取消收藏
            $(e.target).removeClass("collectActive");
            ISFAVORITE = "0"
        } else { //收藏
            $(e.target).addClass("collectActive");
            ISFAVORITE = "1"
        }
        var style = "2"
        if(selectOrgid){
            style = "1"
        }
        var results = sendAjax(modelURL + "/apply/updateApplysFavorite", "POST", {
            id: itemId,
            isFavorite: ISFAVORITE,
            style:style,
            userNo: portaluserno
        });
        if (results.code == 200) {
            if (collect) {
                layer.msg("已取消收藏！", {
                    icon: 1
                })
            } else {
                layer.msg("收藏成功！", {
                    icon: 1
                })
            }

        } else {
            layer.msg("收藏失败！", {
                icon: 5
            })
        }
    });
    //点击运行按钮
    $(".runningBtn").click(function (e) { 
        // initAnalysisMenu () 
        // console.log(applyTanleData,'applyTanleData');
        var name = $(e.target).attr("name");
        var fkMenu = $(e.target).attr("fkMenu"); 
        var status = null 
        applyTanleData.map(item => {
            if (item.NAME == name) {
                status = item.SYSTEM_STATUS
                return 
            }
        }) 
        if (status == 1) {
            window.parent.window.$(".layui-tab-title .layui-this").removeClass("layui-this");
            window.parent.window.$(".layui-tab-title #header_tab2").addClass("layui-this");
            window.parent.window.$("#applicationCenter").hide();
            window.parent.window.$("#fmap").attr("src", "/MapServer/Portal/3DViewer.html?mode=default");
            window.parent.window.$("#fmap").show();
            window.parent.window.$("#fmap").attr("jumpping2Tools", name);
            window.parent.window.$("#fmap").attr("jumpping2ToolsNo", fkMenu);
        } else {
            layer.msg('当前服务已暂停,请联系管理员启动', {icon: 0,time: 1000,shade : [0.5 , '#000' , true]});
        }
        
    })
    //点击 查看授权信息
    $(".permissionInfo").click(function (e) {
        var name = $(e.target).attr("attrName");
        var fkMenu = $(e.target).attr("fkMenu");
        var attrID = $(e.target).attr("attrID");
        var startTime, endTime;
        var results = sendAjax(modelURL + "apply/getLicenseMessage", "POST", {
            id: attrID
        });
        if (results.code == 200) {
            var data = results.data;
            startTime = formatDate(data.starttime);
            endTime = formatDate(data.endtime);
            // $("#permission_againApply").attr("attrName",name)
            // $("#permission_againApply").attr("attrID",attrID)
            // $("#permission_againApply").attr("attrNO",fkMenu)
            // $("#permission_againApply").attr("attrReason",data.reason)
        } else {
            layui.layer.msg("获取信息失败！", {
                icon: 5
            })
        }
        var value = strCompanyData.FK_DEPTTEXT;
        $('#permission_name').text(name);
        $('#permission_department').text(value);
        $('#permission_startTime').text(startTime);
        $('#permission_endTime').text(endTime);
        layer.open({
            type: 1,
            title: "授权信息",
            shadeClose: true, //点击遮罩关闭
            area: ["600px", "400px"],
            content: $("#permissionInfoContent"),
            btn: ['关闭'],
            yes: function (index, layero) {
                layer.close(index);
            }
        });
    });
    //点击再次申请运行权限
    // $(".againApplyPermisssion").click(function(e){
    //     var name = $("#permission_againApply").attr("attrName");
    //     var fkMenu = $("#permission_againApply").attr("attrNO");
    //     var attrID = $("#permission_againApply").attr("attrID"); 
    //     var attrReason = $("#permission_againApply").attr("attrReason"); 
    //     var startTime = getFamtterTimer();
    //     var endTime = "2099-12-31 00:00:00";
    //     $('#apply_reason').val(attrReason);
    //     $('#apply_time').text(startTime);
    //     $('#apply_name').text(name);
    //     $('#apply_person').text(portaluserName);
    //     layer.closeAll();
    //     layer.open({
    //         type: 1,
    //         title: "申请运行",
    //         shadeClose: true, //点击遮罩关闭
    //         area: ["600px", "520px"],
    //         content: $("#applyPermissionContent"),
    //         btn: ['确定','取消'],
    //         yes: function(index, layero) {
    //             var applyReason = $('#apply_reason').val();
    //             var results = sendAjax(modelURL + "apply/applyLicense", "POST", {
    //                 fkUser:portaluserno,
    //                 fkMenu:fkMenu,
    //                 starttime:startTime,
    //                 endtime:endTime,
    //                 reason:applyReason,
    //                 applyperson:portaluserno,
    //                 status:"0"
    //             });
    //             if (results.code == 200) {
    //                 layer.msg("申请成功！",{icon:1})
    //                 layer.close(index);
    //                 fillAppListContent(selectedMenuName);
    //             }else{
    //                 layer.msg("申请失败！",{icon:5})
    //             }
    //         },
    //         btn2:function(index){
    //             layer.close(index);
    //         }
    //     });
    // });
    //点击申请运行按钮
    $(".applyPermission").click(function (e) {
        var applyReason = $('#apply_reason').val("");
        var name = $(e.target).attr("attrName");
        var fkMenu = $(e.target).attr("fkMenu");
        var endTime = "2099-12-31 00:00:00";
        var startTime = getFamtterTimer();
        $('#apply_time').text(startTime);
        $('#apply_name').text(name)
        $('#apply_person').text(portaluserName)
        layer.open({
            type: 1,
            title: "申请运行",
            shadeClose: true, //点击遮罩关闭
            area: ["600px", "520px"],
            content: $("#applyPermissionContent"),
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                var applyReason = $('#apply_reason').val();
                var results = sendAjax(modelURL + "apply/addLicense", "POST", {
                    fkUser: portaluserno,
                    fkMenu: fkMenu,
                    starttime: startTime,
                    endtime: endTime,
                    reason: applyReason,
                    applyperson: portaluserno,
                    status: "0",
                    isfavorite: "0"
                });
                if (results.code == 200) {
                    layer.msg("申请成功！", {
                        icon: 1
                    })
                    layer.close(index);
                    if(selectOrgid){
                        fillAppListContent(selectedMenuName,null,selectOrgid);
                    }else{
                        fillAppListContent(selectedMenuName);
                    }
                }else{
                    layer.msg("申请失败！",{icon:5})
                }
            },
            btn2: function (index) {
                layer.close(index);
            }
        });
    })
}

function initTopEvent() {
    //点击运行管理按钮
    $('#AppRunningManageBtn').click(function () {
        window.parent.window.$(".layui-tab-title .layui-this").removeClass("layui-this");
        window.parent.window.$(".layui-tab-title #header_tab2").addClass("layui-this");
        window.parent.window.$("#applicationCenter").hide();
        window.parent.window.$("#fmap").attr("src", "/MapServer/Portal/3DViewer.html?mode=default");
        window.parent.window.$("#fmap").show();
        window.parent.window.$("#fmap").attr("jumpping", "fromApplicationCenter");
    })
    //点击搜索按钮
    $("#btn_search").click(function () {
        var key = $("#ipt_search").val();
        if(selectOrgid){
            fillAppListContent(selectedMenuName,key,selectOrgid);
        }else{
            fillAppListContent(selectedMenuName,key);

        }
    })
}
function getDataList (menuName,name,Orgid) {
    var key = "";
    if (name) {
        key = name;
    }
    var tableData = null; 
    if (Orgid) {
        $.ajax({
            type: "post",
            async: false,
            url: modelURL + "apply/getApplyByOrgId",
            data:{
                orgId: Orgid,
                userNo:portaluserno
            },
            datatype: "json",
            success: function (res) {
                var data = JSON.parse(res)
                if (data.code == 200) {
                    tableData = data.data 
                    applyTanleData = data.data 
                    tableData.map(item => {
                        return item.REGISTER_DATE = formatDate(item.REGISTER_DATE)
                    })
                } else {
                    layui.layer.msg(data.msg, {
                        icon: 5
                    });
                }
            }
        });
    } else {
        $.ajax({
            type: "post",
            async: false,
            url: modelURL + "apply/getApplys",
            data: {
                menuName: menuName,
                name: key,
                userId: portaluserno
            },
            datatype: "json",
            success: function (res) {
                var data = JSON.parse(res)
                if (data.code == 200) {
                    tableData = data.data 
                    applyTanleData = data.data 
                    tableData.map(item => {
                        return item.REGISTER_DATE = formatDate(item.REGISTER_DATE)
                    })
                } else {
                    layui.layer.msg(data.msg, {
                        icon: 5
                    });
                }
            }
        });
    }

    return tableData;
}

